package libraryPSI;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by User on 19.01.14.
 */
public class BookStorage {
    private Map<Integer, Book> allBooks;
    private int currentId;
    private static final String PATH = "D:\\Library.txt";

    public BookStorage() {
        loadAll();
    }


    //     загрузка списка книг из файла
    private void loadAll() {
        List<String> fromFile = FileMaster.getFileContent(PATH);
        Iterator<String> iter = fromFile.iterator();

        Book tmpBook;
        int maxId = 0;
         String tmp;
        while (iter.hasNext()) {
            tmp = iter.next();
            tmpBook = new Book(tmp);
            Book put;
            put = allBooks.put(tmpBook.getId(), tmpBook);
            if (tmpBook.getId() > maxId) {
                maxId = tmpBook.getId();
            }
        }
        this.currentId = maxId;
    }



    public Book getBookById(int id) {
        return allBooks.get(id);
    }

    public List<Book> getAllBook() {
        return new ArrayList<Book>(allBooks.values());
    }

    public int getNextIdForBook() {
        return ++currentId;
    }

    //добавление книги в список allBooks и запись в файл
    public void addBookToStorage(Book book) {
        allBooks.put(currentId, book);
        flushBooksToFile();
    }

    //Запись книги в файл
    private void flushBooksToFile() {
        List<String> toFile = new ArrayList<String>();
        Iterator<Book> iter = allBooks.values().iterator();
        while (iter.hasNext()) {
            toFile.add(iter.next().toString());
        }
        FileMaster.writeToFile(toFile, PATH);
    }


}
